package com.echoesnet.echoesshortvideo.Activities;

import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.echoesnet.echoesshortvideo.Beans.ErroInfoBean;
import com.echoesnet.echoesshortvideo.Constant.CommonConstant;
import com.echoesnet.echoesshortvideo.R;
import com.echoesnet.echoesshortvideo.Utils.CommonUtils;
import com.echoesnet.echoesshortvideo.Utils.ToastUtils;
import com.echoesnet.echoesshortvideo.ViewModels.LoginViewModel;
import com.echoesnet.echoesshortvideo.views.MyProgressDialog;
import com.orhanobut.logger.Logger;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;

public class LoginAct extends BaseActivity
{
    private static final String TAG = LoginAct.class.getSimpleName();

    @BindView(R.id.cancle)
    TextView tvCancle;
    @BindView(R.id.hint)
    TextView hint;
    @BindView(R.id.phone)
    EditText editText;
    @BindView(R.id.layout_phone)
    LinearLayout layoutPhone;
    @BindView(R.id.wxbtn)
    ImageView ivWeixin;
    @BindView(R.id.layout_channel)
    LinearLayout llChannel;
    @BindView(R.id.tvAgreement)
    TextView tvAgreement;
    @BindView(R.id.nextOk)
    ImageView ivNext;
    @BindView(R.id.clear)
    ImageView clear;
    @BindView(R.id.layout_login)
    LinearLayout llLogin;
    @BindView(R.id.scrollLayout)
    RelativeLayout rl;

    //屏幕高度
    private int screenHeight = 0;
    //软件盘弹起后所占高度阀值
    private int keyHeight = 0;
    //Activity最外层的Layout视图
    @BindView(R.id.root_layout)
    View activityRootView;
    private AlphaAnimation mHideAnimation;
    private AlphaAnimation mShowAnimation;
    private LoginViewModel lModel;
    private MyProgressDialog myProgressDialog;
    public static final int TOP_MARGIN=-340;
    //动画速率
    private static final int ANIM_TIME = 200;

    Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_login);
        ButterKnife.bind(this);

        lModel = new LoginViewModel();
        lModel.getLoginLive().observe(this, new Observer<String>()
        {
            @Override
            public void onChanged(@Nullable String type)
            {
                if (type == null)
                    return;
                Intent intent = null;

                if("ok".equals(type))
                {
                    Toast.makeText(LoginAct.this, "登录成功", Toast.LENGTH_SHORT).show();
                    intent=new Intent(CommonConstant.REQUEST_LOGIN_CODE);
                    LocalBroadcastManager.getInstance(LoginAct.this).sendBroadcast(intent);
                    finish();
                    overridePendingTransition(R.anim.no,R.anim.out_to_bottom_abit);
                    return;
                }


                if ("0".equals(type))//输入登录密码
                {
                    intent = new Intent(LoginAct.this, LoginStepPasswordAct.class);
                    intent.putExtra("phone", editText.getText().toString().trim());
                }
                else//去注册
                {
                    intent = new Intent(LoginAct.this, LoginStepRegisterAct.class);
                    intent.putExtra("phone", editText.getText().toString().trim());
                }
                startActivity(intent);
                new Handler().postDelayed(()->{exitAnim();},100);
                overridePendingTransition(R.anim.out_to_bottom, R.anim.out_to_top_abit);
            }
        });

        lModel.getLoginErroerLive().observe(this, new Observer<ErroInfoBean>()
        {
            @Override
            public void onChanged(@Nullable ErroInfoBean erroInfoBean)
            {
                if(myProgressDialog!=null&&myProgressDialog.isShowing())
                {
                    myProgressDialog.dismiss();
                }
            }
        });

        editText.addTextChangedListener(new TextWatcher()
        {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after)
            {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {
                //随字数改变按钮状态
                changeChannel(s.length());
                if (s.length() < 11)
                {
                    ivNext.setEnabled(false);
                    ivNext.setAlpha(0.5f);
                }
                else
                {
                    ivNext.setEnabled(true);
                    ivNext.setAlpha(1f);
                }
            }

            @Override
            public void afterTextChanged(Editable s)
            {

            }
        });

        // activityRootView = findViewById(R.id.root_layout);

        tvAgreement.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        screenHeight = CommonUtils.getScreenHeight(this);
        keyHeight = screenHeight / 3;
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);

        ivNext.setEnabled(false);
        ivNext.setAlpha(0.5f);

        if (getIntent().getStringExtra("phone") != null)
        {
            editText.setText(getIntent().getStringExtra("phone"));
            llLogin.setVisibility(View.VISIBLE);
            llChannel.setVisibility(View.GONE);
        }

        Selection.setSelection(editText.getText(), editText.getText().length());
        myProgressDialog=new MyProgressDialog().buildDialog(this);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        return true;
    }

    @Override
    protected void onResume()
    {
        super.onResume();
    }

    @OnClick({R.id.cancle, R.id.wxbtn, R.id.nextOk, R.id.clear,R.id.tvAgreement,R.id.root_layout})
    void onViewClick(View view)
    {
        switch (view.getId())
        {
            case R.id.cancle:
                Intent intent=new Intent(CommonConstant.REQUEST_LOGIN_CODE);
                LocalBroadcastManager.getInstance(LoginAct.this).sendBroadcast(intent);
                finish();
                break;
            case R.id.wxbtn:

                myProgressDialog.setDescription("正在登录...").show();
                goWeChatLogin();

                //微信登录
                break;
                case R.id.tvAgreement:

                    startActivity(new Intent(this,MRechargePolicyAct.class));
                break;
            case R.id.clear:
                editText.setText("");
                break;
            case R.id.nextOk:

                //验证手机号
                if (!CommonUtils.verifyInput(3, editText.getText().toString()))
                {
                    //--------------测试时暂时不做限制  上线要拦住！！！
                    ToastUtils.showShort("请输入正确的手机号");
                    return;
                }
                if(CommonUtils.isFastDoubleClick())
                {
                    return;
                }
                //下一步
                if (lModel != null)
                    lModel.checkUserRegisterState(editText.getText().toString().trim());
                break;
        }
    }

    private int state = 0;

    Runnable animRun = new Runnable()
    {
        @Override
        public void run()
        {
            if (state == 1)
                setShowAnimation(llLogin);
            else
                setShowAnimation(llChannel);
        }
    };

    private void goWeChatLogin()
    {
        //三方登录微信
        Platform weChat = ShareSDK.getPlatform(Wechat.NAME);
        weChat.setPlatformActionListener(paListener);
        if (!weChat.isClientValid())
        {
            ToastUtils.showShort("您未安装微信，请先安装");
            return;
        }
        if (weChat.isAuthValid())
        {
            //微信是否授权登录了
            weChat.removeAccount(true);
        }
        weChat.SSOSetting(false);
        //   weChat.authorize();
        weChat.showUser(null);
    }

    PlatformActionListener paListener = new PlatformActionListener()
    {
        @Override
        public void onComplete(final Platform platform, int i, final HashMap<String, Object> hashMap)
        {
            runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    if (lModel != null)
                        lModel.wexinLogin(platform);
                }
            });

        }

        @Override
        public void onError(Platform platform, int i, Throwable throwable)
        {
            Logger.t(TAG).d("error:" + throwable.getMessage());
            runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    if(myProgressDialog!=null&&myProgressDialog.isShowing())
                    {
                        myProgressDialog.dismiss();
                    }
                }
            });
        }

        @Override
        public void onCancel(Platform platform, int i)
        {
            Logger.t(TAG).d("cancle" + i);
            runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    if(myProgressDialog!=null&&myProgressDialog.isShowing())
                    {
                        myProgressDialog.dismiss();
                    }
                }
            });

        }
    };


    private void changeChannel(int count)
    {
        if (count == 0 && state != 0)
        {
            state = 0;
            setHideAnimation(llLogin);
            handler.postDelayed(animRun, ANIM_TIME);
            clear.setVisibility(View.INVISIBLE);
        }
        else if (count != 0 && state == 0)
        {
            state = 1;
            setHideAnimation(llChannel);
            handler.postDelayed(animRun, ANIM_TIME);
            clear.setVisibility(View.VISIBLE);
        }
    }


    /**
     * View渐现动画效果
     */
    public void setShowAnimation(View view)
    {
        if (null != mShowAnimation)
        {
            mShowAnimation.setAnimationListener(null);
            mShowAnimation.cancel();
        }
        else
        {
            mShowAnimation = new AlphaAnimation(0.0f, 1.0f);
            mShowAnimation.setDuration(ANIM_TIME);
            mShowAnimation.setFillAfter(false);

        }

        mShowAnimation.setAnimationListener(new Animation.AnimationListener()
        {

            @Override
            public void onAnimationStart(Animation arg0)
            {
                view.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation arg0)
            {

            }

            @Override
            public void onAnimationEnd(Animation arg0)
            {

            }
        });
        view.startAnimation(mShowAnimation);
    }


    /**
     * View渐隐动画效果
     */
    public void setHideAnimation(View hideView)
    {
        if (null != mHideAnimation)
        {
            handler.removeCallbacks(animRun);
        }
        mHideAnimation = new AlphaAnimation(1.0f, 0.0f);
        mHideAnimation.setDuration(ANIM_TIME);
        mHideAnimation.setFillAfter(false);
        mHideAnimation.setAnimationListener(new Animation.AnimationListener()
        {

            @Override
            public void onAnimationStart(Animation arg0)
            {

            }

            @Override
            public void onAnimationRepeat(Animation arg0)
            {

            }

            @Override
            public void onAnimationEnd(Animation arg0)
            {
                hideView.setVisibility(View.GONE);
            }
        });

        hideView.startAnimation(mHideAnimation);
    }

    private void exitAnim()
    {
        Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.out_to_top_abit);
        animation.setDuration(350);
        animation.setFillAfter(true);
        animation.setFillBefore(false);
        animation.setAnimationListener(new Animation.AnimationListener()
        {
            @Override
            public void onAnimationStart(Animation animation)
            {

            }

            @Override
            public void onAnimationEnd(Animation animation)
            {
                finish();
            }

            @Override
            public void onAnimationRepeat(Animation animation)
            {

            }
        });
        activityRootView.startAnimation(animation);

    }

    ViewTreeObserver.OnGlobalLayoutListener layoutListener = new ViewTreeObserver.OnGlobalLayoutListener()
    {

        @Override
        public void onGlobalLayout()
        {
            activityRootView.getViewTreeObserver().removeOnGlobalLayoutListener(layoutListener);

            Rect r = new Rect();
            activityRootView.getWindowVisibleDisplayFrame(r);

            //现在认为只要控件将Activity向上推的高度超过了1/3屏幕高，就认为软键盘弹起
            if (screenHeight - r.bottom > keyHeight)
            {
                updateViewHeight(true);
            }
            else
            {
                updateViewHeight(false);
            }
            activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);
        }
    };


    @Override
    public void finish()
    {
        super.finish();
        if(myProgressDialog!=null&&myProgressDialog.isShowing())
        {
            myProgressDialog.dismiss();
        }
        overridePendingTransition(R.anim.no, R.anim.out_to_bottom_abit);

    }

    @Override
    public void onBackPressed()
    {
        super.onBackPressed();
        Intent intent=new Intent(CommonConstant.REQUEST_LOGIN_CODE);
        LocalBroadcastManager.getInstance(LoginAct.this).sendBroadcast(intent);
        finish();
    }

    private void updateViewHeight(boolean flag)
    {
        RelativeLayout.LayoutParams pa = (RelativeLayout.LayoutParams) rl.getLayoutParams();
        pa.topMargin = flag ? TOP_MARGIN : 0;
        rl.setLayoutParams(pa);
    }
}